﻿// -----------------------------------------------------------------------
// <copyright file="NVelocityTemplateResolver.cs" company="EPAM Systems">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

namespace MBOP.TextTemplatesCore.Concrete
{
	#region Usings

	using System.IO;
	using System.Text;

	using MBOP.Core.Interfaces.TextTemplatesCore;
	using NVelocity;
	using NVelocity.App;

	#endregion

	/// <summary>
	/// Provides template resolving functionality based on NVelocity engine.
	/// </summary>
	public class NVelocityTemplateResolver : ITemplateResolver
	{
		#region Constants

		/// <summary>
		/// Represents the data template context.
		/// </summary>
		private const string MODEL_NAME = "Model";

		#endregion

		#region ITemplateResolver Members

		/// <summary>
		/// Resolves the current in-memory template.
		/// </summary>
		/// <param name="template">The current template.</param>
		/// <param name="templateModel">The template model.</param>
		/// <returns>The result of the resolving.</returns>
		public string ResolveTemplate(string template, dynamic templateModel)
		{
			VelocityContext context = new VelocityContext();

			context.Put(MODEL_NAME, templateModel);

			string resolvingResult;

			using (StringWriter writer = new StringWriter(new StringBuilder(string.Empty)))
			{
				Velocity.Init();
				Velocity.Evaluate(context, writer, "MyTemplate", template);
				resolvingResult = writer.ToString();
			}

			return resolvingResult;
		}

		#endregion
	}
}
